use crate::api::close_session::close_session;
use crate::media::media_ctrl::stop;
use super::channel::message_channel::IS_ACK;
use super::init::PEER_CONNECTION;
use super::divide_audio_video::{AUDIO_TRACK_STATUS, VIDEO_TRACK_STATUS};
use std::sync::atomic::Ordering;
use super::channel::{input_channel::INPUT_CHANNEL_STATUS, control_channel::CONTROL_CHANNEL_STATUS};
use super::send_rtp_to_udp::STATUS as RTP_STATUS;
// 用于检测xbox端是否主动断开连接, 如果断开连接则关闭所有进程
use super::check_status::PEER_CONNECTION_STATUS;

pub async fn close() {
    // 结束会话, 通过信令通知主机
    close_session().await.unwrap_or(());
    // 结束ffplay和ffmpeg进程
    stop().await;
    // 将message通道的ACK标志位设置为false
    IS_ACK.store(false, Ordering::SeqCst);

    // 关闭peerConnection
    if let Some(peer_conn) = PEER_CONNECTION.lock().await.take() {
        peer_conn.close().await.unwrap();
    }
    let (audio_track_status, video_track_status) = (AUDIO_TRACK_STATUS.clone(), VIDEO_TRACK_STATUS.clone());
    audio_track_status.store(false, Ordering::SeqCst);
    video_track_status.store(false, Ordering::SeqCst);

    let (input_channel_status, control_channel_status) = (INPUT_CHANNEL_STATUS.clone(), CONTROL_CHANNEL_STATUS.clone());
    input_channel_status.store(false, Ordering::SeqCst);
    control_channel_status.store(false, Ordering::SeqCst);

    RTP_STATUS.store(false, Ordering::SeqCst);
    println!("Session closed.");
}

// 检测到xbox端断开连接时调用
pub async fn close_by_xbox_init() {
    tokio::spawn(async {
        loop {
                if !PEER_CONNECTION_STATUS.load(Ordering::SeqCst) {
                    // 将状态设置会true, 避免重复进入
                    PEER_CONNECTION_STATUS.store(true, Ordering::SeqCst);
                    close().await;
                }
                // 防止异步阻塞
                tokio::time::sleep(std::time::Duration::from_secs(2)).await
        }
    });
}
